﻿using System;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using Avalonia.Threading;
using FluentAvalonia.UI.Controls;
using LiveHub.AvaloniaApp.Dialogs;
using LiveHub.AvaloniaApp.ViewModels.Pages;
using LiveHub.AvaloniaApp.Views;
using LiveHub.DataModels;
using Microsoft.AspNetCore.SignalR.Client;

namespace LiveHub.AvaloniaApp.Pages;

public partial class ChatView : UserControl
{
    public ChatView()
    {
        InitializeComponent();
    }

    #region Data

    public UserModel User { get; private set; } = new();

    protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        if (DataContext is not ChatViewModel model) return;
        User = model.User;
        await model.ToChatGroup();
    }

    #endregion

    #region Chat

    private HubConnection? hubConnection;

    protected override async void OnInitialized()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(new Uri($"{ModelData.ChatApiUrl}/LiveChat"))
            .Build();

        if (DataContext is not ChatViewModel model) return;

        hubConnection.On<MessageModel, bool>("ReceiveMessage", (message, isAdd) =>
        {
            if (isAdd)
            {
                model.Messages.Add(message);
                if (message.GetAtUser().All(x => x.Contains(User.UserName))
                    && message.User.UserId == User.UserId) return;
                Dispatcher.UIThread.Post(() =>
                {
                    var main = ViewOpera.GetView<MainWindow>(this);
                    if (main == null) return;
                    main.NotificationShow("消息提示", $"{message.User.UserName}@了你");
                });
            }
            else
            {
                if (message.UserId != User.UserId) return;
                var m = model.Messages.FirstOrDefault(x => x.MessageId == message.MessageId);
                if (m == null) return;
                model.Messages.Remove(m);
            }
        });

        await hubConnection.StartAsync();
    }

    private async void SendClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not ChatViewModel model) return;
        if ( hubConnection is null || string.IsNullOrEmpty(MessageBox.Text)) return;
        await hubConnection.SendAsync("SendMessage", model.Group.GroupId,
            new MessageModel() { Body = MessageBox.Text, UserId = model.User.UserId, User = model.User }, true);
        MessageBox.Text = "";
    }

    #endregion

    #region ChatHeader

    private async void UsersClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not ChatViewModel model) return;
        var td = new TaskDialog
        {
            Title = "LiveHub",
            Header = $"{model.Group.Name}",
            Content = new UsersDialog(model.Group.Users),
            IconSource = new SymbolIconSource { Symbol = Symbol.People },
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Footer = null,
            Buttons =
            {
                TaskDialogButton.OKButton
            },
            XamlRoot = (Visual)VisualRoot!
        };

        await td.ShowAsync();
    }

    private async void ShareClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top?.Clipboard == null) return;
        if (DataContext is not ChatViewModel model) return;
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        await main.Copy($"{User.UserName} 邀请您加入{model.Group.Name} : {model.Group.GroupId}", "LiveHub", "分享成功");
    }

    #endregion

    #region Word

    private void BoldClick(object? sender, RoutedEventArgs e)
    {
        AddText("****");
    }

    private void ItalicClick(object? sender, RoutedEventArgs e)
    {
        AddText("**");
    }

    private void UnderlineClick(object? sender, RoutedEventArgs e)
    {
        AddText("____");
    }

    private async void CopyClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(MessageBox.Text)) return;
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        await main.Copy(MessageBox.Text, "LiveHub", "粘贴成功");
    }

    private async void PasteClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        MessageBox.Text += await top?.Clipboard?.GetTextAsync()!;
    }

    #endregion

    #region Message

    private async void WithdrawClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not ChatViewModel model) return;
        if (sender is not Control control) return;
        if (control.DataContext is not MessageModel message) return;
        if (!string.IsNullOrEmpty(message.Time))
        {
            var time = DateTime.Parse(message.Time);
            if (time.AddMinutes(5) < DateTime.Now)
            {
                var main = ViewOpera.GetView<MainWindow>(this);
                main?.NotificationShow("提示", "消息撤回时间已过", NotificationType.Warning);
                return;
            }
        }

        if (hubConnection is null) return;
        await hubConnection.SendAsync("SendMessage", model.Group.GroupId, message, false);
    }

    private async void ShowUserViewClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not MessageModel model) return;
        var td = new TaskDialog
        {
            Title = "LiveHub",
            Content = new UserDialog(model.User),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Footer = null,
            Buttons =
            {
                TaskDialogButton.OKButton
            },
            XamlRoot = (Visual)VisualRoot!
        };

        await td.ShowAsync();
    }

    private void AtTheUserClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        var data = ViewOpera.GetViewData<MessageModel>(control);
        if (data == null) return;
        AddText($"@{data.User.UserName} ");
    }

    private async void ShareTheMessageClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not MessageModel model) return;
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        var share = $"{User.UserName} 分享了这条消息 :{model.Body} \n 来自 {model.User.UserName}";
        await main.Copy(share, "分享成功", share);
    }

    private async void CopyTheMessageClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not MessageModel model) return;
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        await main.Copy(model.Body, "LiveHub", "复制成功");
    }

    #endregion

    #region Func

    private void AddText(string text)
    {
        if (string.IsNullOrEmpty(MessageBox.Text))
        {
            MessageBox.Text = text;
            return;
        }

        MessageBox.Text = MessageBox.Text?.Insert(MessageBox.CaretIndex, text);
    }

    #endregion

    private void MenuClick(object? sender, RoutedEventArgs e)
    {
        Viewer.IsVisible = !Viewer.IsVisible;
    }
}